/**
 * 
 */
package fr.aprr.geoloc.client.view;


import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.googlecode.gflot.client.DataPoint;
import com.googlecode.gflot.client.PlotModel;
import com.googlecode.gflot.client.Series;
import com.googlecode.gflot.client.SeriesHandler;
import com.googlecode.gflot.client.SimplePlot;
import com.googlecode.gflot.client.event.PlotClickListener;
import com.googlecode.gflot.client.event.PlotHoverListener;
import com.googlecode.gflot.client.event.PlotItem;
import com.googlecode.gflot.client.event.PlotPosition;
import com.googlecode.gflot.client.jsni.Plot;
import com.googlecode.gflot.client.options.AbstractAxisOptions.AxisPosition;
import com.googlecode.gflot.client.options.AxisOptions;
import com.googlecode.gflot.client.options.CrosshairOptions;
import com.googlecode.gflot.client.options.CrosshairOptions.Mode;
import com.googlecode.gflot.client.options.FontOptions;
import com.googlecode.gflot.client.options.GlobalSeriesOptions;
import com.googlecode.gflot.client.options.GridOptions;
import com.googlecode.gflot.client.options.LegendOptions;
import com.googlecode.gflot.client.options.SelectionOptions;
import com.googlecode.gflot.client.options.LegendOptions.LegendPosition;
import com.googlecode.gflot.client.options.LineSeriesOptions;
import com.googlecode.gflot.client.options.PlotOptions;
import com.googlecode.gflot.client.options.PointsSeriesOptions;
import com.googlecode.gflot.client.options.SelectionOptions.SelectionMode;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.event.SelectEvent;

/**
 * @author PHAM
 *
 */
public class FlotChart2 extends Composite implements HasText {

	private static FlotChartUiBinder uiBinder = GWT.create(FlotChartUiBinder.class);

	interface FlotChartUiBinder extends UiBinder<Widget, FlotChart2> {
	}

	/**
	 * Because this class has a default constructor, it can
	 * be used as a binder template. In other words, it can be used in other
	 * *.ui.xml files as follows:
	 * <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
	 *   xmlns:g="urn:import:**user's package**">
	 *  <g:**UserClassName**>Hello!</g:**UserClassName>
	 * </ui:UiBinder>
	 * Note that depending on the widget that is used, it may be necessary to
	 * implement HasHTML instead of HasText.
	 */
	
	
    

    @UiField (provided = true)
	SimplePlot plot;
    
    
	@UiField
	TextButton generate;
	

	@UiField
	Label hoverPoint;
	
	@UiField
	Label cursorPosition;
	
	public FlotChart2(){
		System.out.println("Display Chart");
		
		// Plot model
		PlotModel model = new PlotModel();
		
		// Option
    	PlotOptions plotOption = PlotOptions.create();
    	
    	plotOption.setLegendOptions(LegendOptions.create().setBackgroundOpacity(0).setPosition(LegendPosition.NORTH_WEST));
    	
    	// Option Definir
    	plotOption.setGlobalSeriesOptions(GlobalSeriesOptions.create()
    			.setLineSeriesOptions(LineSeriesOptions.create().setLineWidth(1).setShow(true))
    			.setPointsOptions(PointsSeriesOptions.create().setRadius(2).setShow(true)));
    	
    	// Select selection 
    	plotOption.setSelectionOptions(SelectionOptions.create().setMode(SelectionMode.XY).setColor("red"));
    	
    	//tracking 
        	plotOption.setCrosshairOptions( CrosshairOptions.create().setMode( Mode.X ) );
	
        // Zoom position
        	
        	
    	// Ajoueter XY-Axis
    	plotOption.addXAxisOptions(AxisOptions.create().
    			setPosition(AxisPosition.TOP).setFont(FontOptions.create().
    					setColor("black").setWeight("bold").setStyle("italic")));
        plotOption.addYAxisOptions(AxisOptions.create().
        		setPosition(AxisPosition.BOTTOM).setFont(FontOptions.create().
        				setColor("black").setWeight("bold").setStyle("italic")));
        
        // Option grid
        plotOption.setGridOptions(GridOptions.create().setHoverable(true).setClickable(true));
        
        // Generer Plot
        plot = new SimplePlot(model, plotOption);
        
        // Generer BD
        generateData();
        
		
        // Generer Popup
        final PopupPanel popup = new PopupPanel();
        final Label label = new Label();
        popup.add( label );
       
        // Action Hover Popup
        plot.addHoverListener( new PlotHoverListener() {
			
			public void onPlotHover(Plot plot, PlotPosition position, PlotItem item) {
				// TODO Auto-generated method stub
				
				 if ( position != null )
	                {  
					    cursorPosition.addStyleName("pad-text");
	                    cursorPosition.setText( "Position : {x=" + position.getX() + ", y=" + position.getY() + "}" );
	                }
	                if ( item != null )
	                {
	                    String text = "x: " + item.getDataPoint().getX() + ", y: " + item.getDataPoint().getY();
	                    hoverPoint.addStyleName("pad-text");
	                    hoverPoint.setText( text );

	                    label.setText( text );
	                    popup.setPopupPosition( item.getPageX() + 10, item.getPageY() - 25 );
	                    popup.show();
	                }
	                else
	                {
	                    hoverPoint.setText("vide");
	                    popup.hide();
	                }
			
			}
		}, false);
        
        // Action click
        plot.addClickListener(new PlotClickListener() {
			
			public void onPlotClick(Plot plot, PlotPosition position, PlotItem item) {
				// TODO Auto-generated method stub
				plot.unhighlight();
                if(null != item){
                    plot.highlight(item.getSeries(), item.getDataPoint());
                }
			}
		}, false);
         
        
     // Widget
     		initWidget(uiBinder.createAndBindUi(this));
	
	}
	
	public FlotChart2(String firstName) {
		initWidget(uiBinder.createAndBindUi(this));

		// Can access @UiField after calling createAndBindUi
		generate.setText(firstName);
		System.out.println("FlotChart(String firstName)");
	}
	   
    public void generateData() {
    	int num = Random.nextInt(5);
    	
    	for (int i = 0; i < num; i++) {
			plot.getModel().addSeries(Series.of("Vehicule " +i));
		}
    	
    	for (int i = 0; i < 15; i++) {
			for (SeriesHandler  series : plot.getModel().getHandlers()) {
				series.add(DataPoint.of(Random.nextInt(30),i));
			}
		}
		
	}
    
	
	@UiHandler("generate")
    void onButtonClick(SelectEvent event) {
            plot.getModel().removeAllSeries();
            generateData();
            plot.redraw();
    }
	

	public void setText(String text) {
		generate.setText(text);
	}

	/**
	 * Gets invoked when the default constructor is called
	 * and a string is provided in the ui.xml file.
	 */
	public String getText() {
		return generate.getText();
	}

}
